package com.hk.service.impl.kyc;

import com.hk.commons.ConstantParm;
import com.hk.commons.DateUtil;
import com.hk.commons.JsonUtils;
import com.hk.commons.LongId;
import com.hk.commons.entity.Agreement;
import com.hk.commons.entity.Parameter;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.sys.SysUser;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.kyc.IAgreement;
import com.hk.service.order.IOrderContract;
import com.hk.service.order.IParameter;
import com.hk.service.sys.ISysUser;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import org.hibernate.annotations.common.util.StringHelper;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.stringtemplate.v4.ST;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;


@Service
public class AgreementImpl extends BaseServiceImpl<Agreement> implements IAgreement {

    private static String IFA_ID = "IFA协议";
    private static String IFA_ID_SHOW = "IFA_ID_SHOW";

    private Logger logger = LoggerFactory.getLogger(AgreementImpl.class);


    @Autowired
    private IParameter paraService;

    @Autowired
    private ISysUser sysUserService;

    @Autowired
    private IOrderContract orderContractService;

    @Override
    public Agreement findById(long id) {

        return getById(id);
    }

    @Override
    public Long add(Agreement model) {
        long id = LongId.get();
        model.setCts(System.currentTimeMillis());
        model.setId(id);
        super.save(model);
        return id;
    }

    @Override
    public Long getTQRHId() {


        Parameter parm = paraService.getByName(ConstantParm.TZQRH_ID);

        if (parm == null) {
            logger.error("获取投资确认函配置参数失败");
        }

        Long id = Long.valueOf(parm.getValue01());

        return id;
    }

    @Override
    public String getByInfo(Long id, Long userId, String amt) {

        logger.info("获取协议 strId={}， userId={}, amt={}", id, userId, amt);

        String msg = "";

        SysUser user = null;

        if (userId != null) {
            user = sysUserService.findById(userId);
        }

        logger.info("amt ={}", amt);

        Agreement ag = findById(id);
        if (ag == null && ag.getAgreement() == null) {
            return null;
        }

        try {
            msg = new String(ag.getAgreement(), "UTF-8");

            if (user != null && StringHelper.isNotEmpty(user.getRealName())) {
                msg = msg.replace("张三", user.getRealName());
                logger.info("替换用户姓名");
            }

            if (user != null && StringHelper.isNotEmpty(user.getName())) {
                msg = msg.replace("13466668888", user.getName());
                logger.info("替换用户手机号");
            }

            if (user != null && StringHelper.isNotEmpty(user.getIdentity())) {
                msg = msg.replace("41066666688888888", user.getIdentity());
                logger.info("替换用户身份证号");
            }

            if (user != null && StringHelper.isNotEmpty(user.getIdentity())) {
                msg = msg.replace("签署日期：", "签署日期：" + DateUtil.getCurTimeStr());
                logger.info("替换签署日期");
            }

            if (StringHelper.isNotEmpty(amt)) {
                msg = msg.replace("99999", amt);
                logger.info("替换购买金额");
            }

            //替换日期
            msg = msg.replace("nowDate", DateUtil.getCurTimeStr());

        } catch (Exception e) {
            logger.info("get agreement exception e={}", e);
        }
        return msg;
    }

    @Override
    public String createIFAPdf(SysUser sysUser, Payment payment) {

        String ifaContent = getIfaContent(sysUser, payment);

        String fileName = System.currentTimeMillis() + ".pdf";
        String pdfIfa = orderContractService.createPDFDocument(ifaContent, fileName, false);
        if(pdfIfa == null){
            logger.error("创建不带印章的pdf失败");
            return null;
        }

        logger.info("创建不带印章的pdf成功， pdfFilePath = {}", fileName);
        String pdfIfaFtpResult = this.orderContractService.ftpSave(pdfIfa, pdfIfa, true);

        if(pdfIfaFtpResult == null){
            logger.error("ifa ftp 保存失败");
            return null;
        }
        return pdfIfa;
    }

    @Override
    public String showIFA(SysUser sysUser, Payment payment) {
        Parameter parameter = this.paraService.getByName(AgreementImpl.IFA_ID);
        Long ifaId = Long.valueOf(parameter.getValue01());

        Agreement agreement = this.findById(ifaId);
        String agreeContent = null;
        try {
            String agreeContentTemplate = new String(agreement.getAgreement(), "UTF-8");

            String dateFormat = "Y年M月d日";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
            LocalDateTime now = LocalDateTime.now();

            ST agreementST = new ST(agreeContentTemplate, '$', '$');

            agreementST.add("realName", sysUser.getRealName());
            agreementST.add("ContactPhone", sysUser.getName());
            agreementST.add("ContactAddress", "");
            agreementST.add("identity", sysUser.getIdentity());
            agreementST.add("EmployeeID", "");

            if (payment != null) {
                agreementST.add("AccountName", payment.getAccountName());
                agreementST.add("AccountID", payment.getPaymentNo());
                agreementST.add("BankName", payment.getBankName());
            } else {
                agreementST.add("AccountName", "");
                agreementST.add("AccountID", "");
                agreementST.add("BankName", "");
            }

            agreementST.add("now", now.format(formatter));

            agreeContent = agreementST.render();

            String html = "<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta name=\"viewport\"\n" +
                    "      content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=2.0, user-scalable=yes\"/></head><body>$content$</body></html>";

            ST htmlST = new ST(html, '$', '$');
            htmlST.add("content", agreeContent);
            agreeContent = htmlST.render();

        } catch (Exception e) {
            logger.error("create ifa error", e);
        }

        return agreeContent;
    }

    private String getCode() {
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 12; i++) {
            code += random.nextInt(10);
        }
        return code;
    }



    @Override
    public String createIFAHtml(SysUser sysUser, Payment payment) {

        String pathName = getCode() + ".html";

        //获取合同内容
        String contractMsg = getIfaContent(sysUser, payment);

        //将合同内容转换为pdf格式
        contractMsg = orderContractService.getHtmlContent(contractMsg);


        logger.info("creatHTMLFile pathName ={}", pathName);
        try {
            Path filePath = Paths.get(pathName);
            Files.write(filePath, contractMsg.getBytes("UTF-8"));
        } catch (IOException e) {
            logger.error("创建IFA  HTML 合同 失败 user ID ={}, e={}", sysUser.getId(),  e);
        }




        String respStr = orderContractService.ftpSave(pathName, pathName, true);

        if(respStr == null){
            logger.info("ftp 保存 IFA  HTML 合同 失败 respStr = " + respStr);
            return  null;
        }

        logger.info("ftp保存IFA HTML 合同成功");

        return pathName;
    }

    public String getIfaContent(SysUser sysUser, Payment payment) {
        Parameter parameter = this.paraService.getByName(AgreementImpl.IFA_ID);
        Long ifaId = Long.valueOf(parameter.getValue01());

        Agreement agreement = this.findById(ifaId);
        String agreeContentHTML = null;
        try {
            String agreeContentTemplate = new String(agreement.getAgreement(), "UTF-8");
            String dateFormat = "Y年M月d日";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
            LocalDateTime now = LocalDateTime.now();

            ST agreementST = new ST(agreeContentTemplate, '$', '$');

            agreementST.add("realName", sysUser.getRealName());
            agreementST.add("ContactPhone", sysUser.getName());
            agreementST.add("ContactAddress", "");
            agreementST.add("identity", sysUser.getIdentity());
            agreementST.add("EmployeeID", "");

            agreementST.add("AccountName", payment.getAccountName());
            agreementST.add("AccountID", payment.getPaymentNo());
            agreementST.add("BankName", payment.getBankName());
            agreementST.add("now", now.format(formatter));

            agreeContentHTML = agreementST.render();


        } catch (Exception e) {
            logger.error("get ifa content error", e);
        }

        return agreeContentHTML;
    }





}
